import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:im_app/im/page/bloc/SessionListCubit.dart';
import 'package:im_app/im/page/view/component/GroupIconView.dart';
import 'package:im_app/im/page/view/component/UserIconView.dart';
import 'package:im_app/im/pojo/Enums.dart';
import 'package:im_app/im/util/DbUtil.dart';
import 'package:im_app/im/util/ImCacheFactory.dart';
import 'package:im_app/im/util/ImSingleton.dart';
import 'package:logger/logger.dart';
import 'package:provider/provider.dart';

import '../../../../dao/ImSessionDao.dart';
import '../../../../pojo/ImPojo.dart';
import '../../../../pojo/UiPojo.dart';
import '../../../../util/ImConstant.dart';
import '../../../sub/UserInfoPage.dart';
import '../../ListSeparator.dart';

class UserAndGroupItemView extends StatelessWidget {
  final _logger = Logger(
    printer: PrettyPrinter(),
  );

  final ImUserAndGroup userAndGroup;
  final ImUserAndGroup? preUserGroup;

  UserAndGroupItemView({required this.userAndGroup, this.preUserGroup, super.key});

  @override
  Widget build(BuildContext context) {
    if (preUserGroup == null || userAndGroup.firstLetter != preUserGroup?.firstLetter) {
      return Column(
        children: [
          _buildGroupTitle(),
          _buildUserAndGroupPane(context),
          Padding(
            padding: const EdgeInsets.only(top: 1, bottom: 1),
            child: ListSeparator(),
          ),
        ],
      );
    }
    return Column(
      children: [
        _buildUserAndGroupPane(context),
        Padding(
          padding: const EdgeInsets.only(top: 1, bottom: 1),
          child: ListSeparator(),
        ),
      ],
    );
  }

  Widget _buildUserAndGroupPane(BuildContext context) {
    return ListTile(
        dense: true,
        contentPadding: const EdgeInsets.only(top: 5, bottom: 5, left: 10, right: 10),
        leading: userAndGroup?.type == UserAndGroupType.user ?
        UserIconView(user: userAndGroup.user!, iconSize: ImConstant.IM_USER_ICON_SIZE - 10,) :
        GroupIconView(group: userAndGroup.group!, iconSize: ImConstant.IM_USER_ICON_SIZE - 10),
        title: Text("${userAndGroup?.name ?? ''}",
            style: const TextStyle(fontSize: ImConstant.IM_DEFAULT_SIZE, fontWeight: FontWeight.w300)),
        onTap: () {
          // _showSendMessage(context, userGroup);
          _showUserInfo(context, userAndGroup);
        });
  }

  Widget _buildGroupTitle() {
    return Container(
      color: ImConstant.IM_LIST_GROUP_COLOR,
      padding: const EdgeInsets.only(left: 10),
      child: Row(
        children: [
          Text(
            (userAndGroup.firstLetter ?? "#").toUpperCase(),
            style: const TextStyle(fontSize: 16),
          )
        ],
      ),
    );
  }

  void _showUserInfo(BuildContext context, ImUserAndGroup imUserGroup) async {
    _logger.i("show userId: ${imUserGroup.code}");
    var userId = await ImSingleton.getInstance().session.userId;

    if (imUserGroup.type == UserAndGroupType.user) {
      var imUser = await ImCacheFactory.getInstance().getImUser(imUserGroup.code);
      if (context.mounted) {
        Navigator.push(context, MaterialPageRoute(builder: (BuildContext context) {
          return UserInfoPage(user: imUser!);
        }));
      }
    } else {
      // var imGroup = await ImCacheFactory.getInstance().getImGroup(userId!, imUserGroup.code);
      var sessionDao = ImSessionDao();
      var imSession = await sessionDao.getByGroupCodeAndUserId(imUserGroup.code, userId!);
      if (context.mounted) {
        Navigator.of(context).pushNamed("/MessageSendPage", arguments: {"id": imSession?.id!, "name": imSession?.name});
      }
    }
  }

  void _showSendMessage(BuildContext context, ImUserAndGroup imUserGroup) async {
    _logger.i("show userId: ${imUserGroup.code}");
    var userId = await ImSingleton.getInstance().session.userId;

    late ImSession imSession;
    var sessionDao = ImSessionDao();

    if (imUserGroup.type == UserAndGroupType.user) {
      var session = await sessionDao.getByUserId(userId!, userId, imUserGroup.code);
      if (session == null) {
        var imUser = await ImCacheFactory.getInstance().getImUser(imUserGroup.code);
        imSession = ImSession.buildWithUser(userId, imUser);
        await sessionDao.insert(imSession);
      } else {
        imSession = session;
      }
    } else {
      var session = await sessionDao.getByGroupCodeAndUserId(imUserGroup.code, userId!);
      if (session == null) {
        var imGroup = await ImCacheFactory.getInstance().getImGroup(userId!, imUserGroup.code);
        imSession = ImSession.buildWithGroup(userId, imGroup!);
        await sessionDao.insert(imSession);
      } else {
        imSession = session;
      }
    }

    SessionListCubit sessionListCubit = context.read<SessionListCubit>();
    sessionListCubit.addSession(imSession);

    Navigator.of(context).pushNamedAndRemoveUntil("/MessageSendPage", ModalRoute.withName('/MainPage'), arguments: {"id": imSession?.id!, "name": imSession?.name});
  }
}
